<template>
  <div class="main-layout">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <div class="header-logo">R</div>
        <div class="header-title">通用商品后台管理系统</div>
        <div class="header-quote">古之立大志者,不惟有超世之才,亦必有坚韧不拔之志</div>
      </div>
      <div class="header-right">
        <div class="header-date">{{ currentDateTime }}</div>
        <el-dropdown @command="handleUserCommand">
          <span class="user-info">
            <el-icon><User /></el-icon>
            {{ userInfo?.username || '理程' }}
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人资料</el-dropdown-item>
              <el-dropdown-item command="settings">系统设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <div class="content-wrapper">
      <!-- 左侧导航栏 -->
      <aside class="sidebar">
        <div class="sidebar-header">
          <el-icon><Menu /></el-icon>
          <span class="sidebar-title">Pages</span>
        </div>
        
        <nav class="sidebar-nav">
          <div 
            v-for="item in menuItems" 
            :key="item.key"
            class="nav-group"
          >
            <div 
              class="nav-item"
              :class="{ active: item.active, expanded: item.expanded }"
              @click="toggleMenu(item)"
            >
              <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
              <span>{{ item.title }}</span>
              <el-icon v-if="item.children" class="arrow">
                <ArrowDown v-if="item.expanded" />
                <ArrowRight v-else />
              </el-icon>
            </div>
            
            <div v-if="item.expanded && item.children" class="nav-submenu">
              <div 
                v-for="child in item.children" 
                :key="child.key"
                class="nav-item"
                :class="{ active: child.active }"
                @click="navigateTo(child.path)"
              >
                <span>{{ child.title }}</span>
              </div>
            </div>
          </div>
        </nav>
        
        <div class="sidebar-footer">
          <span>Use < and > keys to move between pages</span>
        </div>
      </aside>

      <!-- 主内容区域 -->
      <main class="main-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item 
              v-for="item in breadcrumbs" 
              :key="item.path"
              :to="item.path"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!-- 标签页导航 -->
        <div class="content-tabs">
          <div 
            v-for="tab in tabs" 
            :key="tab.key"
            class="tab-item"
            :class="{ active: tab.active }"
            @click="navigateTo(tab.path)"
          >
            {{ tab.title }}
          </div>
        </div>

        <!-- 路由内容 -->
        <router-view />
      </main>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { 
  User, ArrowDown, ArrowRight, Menu,
  Goods, UserFilled, Shop, Sell, ShoppingCart, 
  Box, Money, Setting
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

export default {
  name: 'Layout',
  components: {
    User, ArrowDown, ArrowRight, Menu,
    Goods, UserFilled, Shop, Sell, ShoppingCart,
    Box, Money, Setting
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const authStore = useAuthStore()
    
    const currentDateTime = ref('')
    let timer = null

    // 用户信息
    const userInfo = computed(() => authStore.userInfo)

    // 菜单项
    const menuItems = ref([
      {
        key: 'login',
        title: '登陆',
        icon: 'User',
        path: '/login',
        active: false,
        expanded: false
      },
      {
        key: 'products',
        title: '商品管理',
        icon: 'Goods',
        active: false,
        expanded: false,
        children: [
          { key: 'product-add', title: '新增', path: '/products/add' },
          { key: 'product-detail', title: '详细信息', path: '/products/detail' }
        ]
      },
      {
        key: 'customers',
        title: '客户管理',
        icon: 'UserFilled',
        active: false,
        expanded: false,
        children: [
          { key: 'customer-add', title: '客户新增', path: '/customers/add' },
          { key: 'customer-detail', title: '客户详细信息', path: '/customers/detail' }
        ]
      },
      {
        key: 'suppliers',
        title: '供应商管理',
        icon: 'Shop',
        active: false,
        expanded: false,
        children: [
          { key: 'supplier-add', title: '供应商新增', path: '/suppliers/add' },
          { key: 'supplier-detail', title: '供应商详细信息', path: '/suppliers/detail' }
        ]
      },
      {
        key: 'sales',
        title: '销售管理',
        icon: 'Sell',
        active: false,
        expanded: true,
        children: [
          { key: 'sales-order', title: '销售订单', path: '/sales/orders' },
          { key: 'sales-contract', title: '销售合同', path: '/sales/contracts' },
          { key: 'delivery-plan', title: '交付计划', path: '/sales/delivery' },
          { key: 'sales-shipment', title: '销售发货', path: '/sales/shipment' },
          { key: 'sales-return', title: '销售退货', path: '/sales/return' },
          { key: 'sales-invoice', title: '销售开票', path: '/sales/invoice' }
        ]
      },
      {
        key: 'menus',
        title: '菜单管理',
        icon: 'Menu',
        active: false,
        expanded: true,
        children: [
          { key: 'menu-list', title: '菜单列表', path: '/menus' },
          { key: 'menu-permission', title: '菜单权限', path: '/menus/permission' },
          { key: 'menu-role', title: '角色菜单', path: '/menus/role' }
        ]
      },
      {
        key: 'inventory',
        title: '库存管理',
        icon: 'Box',
        active: false,
        expanded: true,
        children: [
          { key: 'inbound', title: '入库管理', path: '/inventory/inbound' },
          { key: 'outbound', title: '出库管理', path: '/inventory/outbound' },
          { key: 'transfer', title: '调拨管理', path: '/inventory/transfer' },
          { key: 'count', title: '库存盘点', path: '/inventory/count' }
        ]
      },
      {
        key: 'warehouse',
        title: '仓库管理',
        icon: 'Box',
        active: false,
        expanded: false
      },
      {
        key: 'logistics',
        title: '物流管理',
        icon: 'Truck',
        active: false,
        expanded: false
      },
      {
        key: 'capital',
        title: '资金管理',
        icon: 'Money',
        active: false,
        expanded: true,
        children: [
          { key: 'receivable', title: '应收款', path: '/capital/receivable' },
          { key: 'payable', title: '应付款', path: '/capital/payable' }
        ]
      },
      {
        key: 'system',
        title: '系统管理',
        icon: 'Setting',
        active: false,
        expanded: false,
        children: [
          { key: 'roles', title: '角色管理', path: '/roles' },
          { key: 'users', title: '用户管理', path: '/users' }
        ]
      }
    ])

    // 标签页
    const tabs = ref([
      { key: 'products', title: '商品管理', path: '/products', active: false },
      { key: 'customers', title: '客户管理', path: '/customers', active: false },
      { key: 'suppliers', title: '供应商管理', path: '/suppliers', active: false },
      { key: 'sales', title: '销售管理', path: '/sales', active: false },
      { key: 'menus', title: '菜单管理', path: '/menus', active: false },
      { key: 'inventory', title: '库存管理', path: '/inventory', active: false },
      { key: 'capital', title: '资金管理', path: '/capital', active: false },
      { key: 'system', title: '系统管理', path: '/system', active: false }
    ])

    // 面包屑
    const breadcrumbs = computed(() => {
      const path = route.path
      const segments = path.split('/').filter(Boolean)
      const result = [{ title: '首页', path: '/' }]
      
      let currentPath = ''
      segments.forEach(segment => {
        currentPath += `/${segment}`
        const menuItem = findMenuItemByPath(currentPath)
        if (menuItem) {
          result.push({ title: menuItem.title, path: currentPath })
        }
      })
      
      return result
    })

    // 更新当前时间
    const updateDateTime = () => {
      currentDateTime.value = dayjs().format('YYYY年MM月DD日 dddd HH:mm')
    }

    // 切换菜单展开/收起
    const toggleMenu = (item) => {
      if (item.children) {
        item.expanded = !item.expanded
      } else {
        navigateTo(item.path)
      }
    }

    // 导航到指定路径
    const navigateTo = (path) => {
      if (path) {
        router.push(path)
      }
    }

    // 根据路径查找菜单项
    const findMenuItemByPath = (path) => {
      for (const item of menuItems.value) {
        if (item.path === path) return item
        if (item.children) {
          for (const child of item.children) {
            if (child.path === path) return child
          }
        }
      }
      return null
    }

    // 更新菜单激活状态
    const updateMenuActive = () => {
      const currentPath = route.path
      
      // 重置所有菜单项状态
      menuItems.value.forEach(item => {
        item.active = false
        if (item.children) {
          item.children.forEach(child => {
            child.active = false
          })
        }
      })
      
      // 设置当前激活的菜单项
      const currentItem = findMenuItemByPath(currentPath)
      if (currentItem) {
        currentItem.active = true
        // 如果是子菜单，也要激活父菜单
        for (const item of menuItems.value) {
          if (item.children) {
            const child = item.children.find(c => c.path === currentPath)
            if (child) {
              child.active = true
              item.expanded = true
            }
          }
        }
      }
      
      // 更新标签页激活状态
      tabs.value.forEach(tab => {
        tab.active = currentPath.startsWith(tab.path)
      })
    }

    // 处理用户下拉菜单命令
    const handleUserCommand = async (command) => {
      switch (command) {
        case 'profile':
          ElMessage.info('个人资料功能开发中...')
          break
        case 'settings':
          ElMessage.info('系统设置功能开发中...')
          break
        case 'logout':
          try {
            await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
            await authStore.logout()
          } catch (error) {
            // 用户取消
          }
          break
      }
    }

    onMounted(() => {
      updateDateTime()
      updateMenuActive()
      
      // 设置定时器更新时间
      timer = setInterval(updateDateTime, 1000)
    })

    onUnmounted(() => {
      if (timer) {
        clearInterval(timer)
      }
    })

    // 监听路由变化
    router.afterEach(() => {
      updateMenuActive()
    })

    return {
      currentDateTime,
      userInfo,
      menuItems,
      tabs,
      breadcrumbs,
      toggleMenu,
      navigateTo,
      handleUserCommand
    }
  }
}
</script>

<style scoped>
.main-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: var(--primary-color);
  color: white;
  padding: 0 20px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-logo {
  width: 40px;
  height: 40px;
  background: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary-color);
  font-size: 18px;
  font-weight: bold;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
}

.header-quote {
  font-size: 12px;
  opacity: 0.9;
  margin-left: 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-date {
  font-size: 14px;
  opacity: 0.9;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.1);
}

.content-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background: white;
  border-right: 1px solid var(--border-light);
  overflow-y: auto;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid var(--border-light);
  display: flex;
  align-items: center;
  gap: 10px;
}

.sidebar-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.sidebar-nav {
  padding: 10px 0;
}

.nav-group {
  margin-bottom: 5px;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: var(--text-regular);
  text-decoration: none;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
}

.nav-item:hover {
  background: var(--background-base);
  color: var(--primary-color);
}

.nav-item.active {
  background: var(--primary-color);
  color: white;
}

.nav-item .icon {
  margin-right: 10px;
  width: 16px;
  height: 16px;
}

.nav-item .arrow {
  margin-left: auto;
  transition: transform 0.3s;
}

.nav-item.expanded .arrow {
  transform: rotate(90deg);
}

.nav-submenu {
  background: var(--background-lighter);
  border-left: 3px solid var(--primary-color);
}

.nav-submenu .nav-item {
  padding-left: 40px;
  font-size: 14px;
}

.sidebar-footer {
  padding: 20px;
  text-align: center;
  font-size: 12px;
  color: var(--text-secondary);
  border-top: 1px solid var(--border-light);
}

.main-content {
  flex: 1;
  background: var(--background-base);
  overflow-y: auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.content-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.tab-item {
  padding: 8px 16px;
  background: white;
  border: 1px solid var(--border-base);
  border-radius: 4px;
  color: var(--text-regular);
  text-decoration: none;
  transition: all 0.3s;
  cursor: pointer;
}

.tab-item:hover {
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.tab-item.active {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-wrapper {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
  }
  
  .header-quote {
    display: none;
  }
  
  .content-tabs {
    flex-direction: column;
  }
}
</style>
